#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = '__Jack__'
import re
from lib2to3.pygram import pattern_grammar

from fastapi import APIRouter, Depends, HTTPException, Body
from fastapi.responses import JSONResponse, Response
from database import get_db
from sqlalchemy.orm import Session
from app.yg_crm import schemas, crud, orm
from typing import List, Optional, Annotated
from utility.utility import result, RespResult, json_result_reps
from utility.myJsonHandler import orjson_dumps
from log import log
from sqlalchemy import Row
from database import db_conf

sys_router = APIRouter()


@sys_router.post("/getDataBySql")
def getDataBySql(db: Session = Depends(get_db), isUpdate: Optional[bool] = Body(embed=True, default=False), groupedBy: Optional[str] = Body(embed=True, default=None), sql: str = Body(embed=True,
                                                                examples=[
                                                                    {
                                                                        "sql": "select name from user",
                                                                    }
                                                                ]
                                                                )):

    def replace_str_with_quotes(txt, pattern):
        def replacer(match):
            #print("|" + match.group(0) + "|")
            return f' "{match.group(1)}"'

        pattern = re.compile(pattern, re.IGNORECASE)
        return pattern.sub(replacer, txt, count=1)

    # sql兼容性处理
    if 'pg' in db_conf.type:
        pattern_table = "(?:(?<=update)|(?<=from)|(?<=join))\s+([\w\u4e00-\u9fa5_]+)(?=[\s\,]?)"
        sql = replace_str_with_quotes(sql, pattern_table)

    log.info("isUpdate:{}", isUpdate)
    log.info("sql{}", sql)
    data = crud.getDataBySql(db, sql, isUpdate, groupedBy)

    return json_result_reps(data=data)
